# 反转字符串中的单词III: https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/

class Solution:
    def reverseWords(self, s: str) -> str:
        s = list(s)
        i = 0   
        def reverse(left, right):
            while left < right:
                s[left], s[right] = s[right], s[left]
                left += 1; right -= 1

        while i < len(s):    
            while i < len(s) and s[i] == ' ': i += 1 
            left = i
            while i < len(s) and s[i] != ' ': i += 1
            right = i - 1
            reverse(left, right)

        return ''.join(s)

s1 = "Let's take LeetCode contest"

s = Solution()
rst = s.reverseWords(s1)
print(rst)


# 优化一下代码的写法，少用几个变量
class Solution:
    def reverseWords(self, s: str) -> str:
        
        def reverse(left, right):
            while left < right:
                s[left], s[right] = s[right], s[left]
                left += 1; right -= 1
                
        s, left = list(s), 0
        while left < len(s):    
            right = left
            while left < len(s) and s[left] == ' ': left += 1 
            while right + 1 < len(s) and s[right + 1] != ' ': right += 1
            # 不可变对象当做参数传递的是值（值传递, 函数中运转，不改变这里left，right的值）
            reverse(left, right)
            left = right + 1

        return ''.join(s)